﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace OINS
{
    public partial class mainWindow : Form
    {
        
        List<Client2> clients = new List<Client2>();
        List<String> askers = new List<String>();
        ActiveHosts active = new ActiveHosts();
        addHostWindow ramka;
        Resources res = new Resources();
        Server2 ser;
        Thread forServing;
        Thread rozglaszanie;
        Thread search;
        byte[] b=new byte[4];
        int connect = 0;
        String sciezka;
        String sciezka2;
        public mainWindow()
        {
            
            InitializeComponent();
            res.LoadTheList();
            
           
            ser = new Server2(res.ListOfFiles, ref clients);
            disconnectToolStripMenuItem.Enabled = false;
            button1.Enabled = false;
          
            forServing = new Thread(new ThreadStart(ser.Run));
            rozglaszanie = new Thread(new ThreadStart(SearchForHost));
            search = new Thread(new ThreadStart(Search));
            rozglaszanie.Start();
            
            
            
        }

        void Search()
        {
            UdpClient udpClient = new UdpClient(8080);
            while (true)
            {
                IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
                Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
                string returnData = Encoding.ASCII.GetString(receiveBytes);
                System.Console.WriteLine(returnData);

                int lic = active.activeHosts.Count();
                string name = "activehost(" + Convert.ToString(lic) + ")";
                int pom = 0;
                if (returnData != ser.GetMyIP())
                {
                    for (int i = 0; i < lic; i++)
                    {
                        if (active.activeHosts.ElementAt(i).IP == returnData)
                            pom++;
                    }
                    if (pom == 0)
                    {
                        active.Add(name, returnData);
                        clients.Add(new Client2(active.activeHosts.ElementAt(active.activeHosts.Count - 1).IP));
                        if (clients.ElementAt(active.activeHosts.Count - 1).Connect())
                            connect++;

                    }
                    if (connect >= 1)
                    {

                        toolStripStatusLabel1.Text = "Connected";
                      
                    }
                    else
                        toolStripStatusLabel1.Text = "No connections";

                }
                    
            }

        }
        
        
        void SearchForHost()
        {
            do
            {
                UdpClient udpClient = new UdpClient("255.255.255.255", 8080);
                Byte[] sendBytes = Encoding.ASCII.GetBytes(ser.GetMyIP());
                udpClient.Send(sendBytes, sendBytes.Length);
                Thread.Sleep(2000);
            }while(true);


        }
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {

        }

        private void authorsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("AP2P is designed by Maciej Strzelecki and Adam Zadura");



        }

        private void connectToolStripMenuItem_Click(object sender, EventArgs e)
        {

            forServing.Start();
            search.Start();
            toolStripStatusLabel1.Text = "Connecting...";
            connectToolStripMenuItem.Enabled = false;
            disconnectToolStripMenuItem.Enabled = true;
            button1.Enabled = true;         
           
            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }
       
        

       
        private void showListOfSharedFilesToolStripMenuItem_Click(object sender, EventArgs e)
        {

            listAddedFilesWindow a = new listAddedFilesWindow();
            a.Show();
            res.LoadTheList();
            a.writeFiles(res.ListOfFiles);
        }

        private void disconnectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IPHostEntry ip = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName());
            string IP = ip.AddressList[0].ToString();
            UdpClient udpClient = new UdpClient("255.255.255.255", 8080);
            Byte[] sendBytes = Encoding.ASCII.GetBytes("BYE " + IP);
            udpClient.Send(sendBytes, sendBytes.Length);
            connect--;
            disconnectToolStripMenuItem.Enabled = false;
            connectToolStripMenuItem.Enabled = true;
            toolStripStatusLabel1.Text = "No connections";
            button1.Enabled = false;
            clients.ElementAt(0).Disconnect();
            clients.Clear();
       
        }

        private void yourIPIsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show(ser.GetMyIP());
        }

        private void button1_Click(object sender, EventArgs e)
        {
           
            System.Random x = new Random(System.DateTime.Now.Millisecond);
            int a = x.Next(0, active.nrOfHosts-1);
            System.Console.WriteLine("MAINWINDOW: wybralem: " + a);
            System.Console.WriteLine("MOJE IP TO " + ser.GetMyIP());
            askers.Add(ser.GetMyIP());
       
            
            clients.ElementAt(a).PushSearch(filenameLabel.Text, askers);
        }

        private void addIPToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ramka = new addHostWindow();
            ramka.Show();
            
        }

        private void showActiveHostsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
            
            listActiveHostWindow a = new listActiveHostWindow();
            a.Show();
            a.writeHosts(active.activeHosts);
            
            
        }

        private void addFolderToShareToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dlg = new FolderBrowserDialog();

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                res.AddFolderToResources(dlg.SelectedPath);
                res.SaveTheList();
            }

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void mainWindow_FormClosed(object sender, FormClosedEventArgs e)
        {
            System.Console.WriteLine(forServing.ThreadState);
            forServing.Abort();
            ser.Koniec();
            ser.KonczWatek();
            rozglaszanie.Abort();
            search.Abort();
            System.Console.WriteLine(rozglaszanie.ThreadState);
            System.Console.WriteLine(search.ThreadState);
            System.Console.WriteLine(forServing.ThreadState);
            Application.Exit();

        }

        private void filenameLabel_TextChanged(object sender, EventArgs e)
        {

        }

        public void SaveTheDir(String dir)
        {
          

            StreamWriter stream = new StreamWriter("dir.txt", false);
            
                stream.WriteLine(dir);
            stream.Close();
        }
        private void setDownloadPathToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dlg = new FolderBrowserDialog();

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                SaveTheDir(dlg.SelectedPath);
               
            
            }
        }
    }
}
